<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 使用组件 -->
      <PageTools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button v-if="checkPermission('importEmployees')" size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="EmployeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="头像" sortable="" width="200px">
            <!-- 使用自定义指令 与生成二维码 -->
            <template #default="{row}">
              <img
                v-imgerr="require('@/assets/common/meinv.jpg')"
                :src="row.staffPhoto"
                class="avatar"
                @click="showQRcode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <!-- 使用作用域插槽获取点击的数据 -->
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageEmployee.size" @current-change="currentChange" />
        </el-row>
      </el-card>
      <!-- 添加员工弹窗 -->
      <AddEmployee :show-dialog="showDialog" />
      <!-- 二维码弹窗 -->
      <el-dialog title="头像二维码" :visible="isShowQRcode" @close="isShowQRcode=false">
        <el-row type="flex" justify="center">
          <canvas ref="MyCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色管理弹窗 -->
      <AssignRole
        ref="assignRole"
        :show-assign-role.sync="showAssignRole"
      />
    </div>
  </div>
</template>

<script>
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { getEmployeeList, delEmployee } from '@/api/employee'
import employeeEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import qrcode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      pageEmployee: { // 设置页码
        page: 1,
        size: 5
      },
      EmployeeList: [], // 初始数据
      total: 0, // 数据总条数
      showDialog: false,
      isShowQRcode: false,
      showAssignRole: false
    }
  },
  created() {
    // 获取初始数据
    this.getEmployeeList()
  },
  methods: {
    // 显示角色弹窗
    async  assignRole(id) {
      // 调用子组件方法
      // 防止第二次点击弹窗数据闪烁解决方法一 添加async await
      await this.$refs.assignRole.getUserMessage(id)
      this.showAssignRole = true
    },
    // 显示弹窗生成二维码
    showQRcode(url) {
      this.isShowQRcode = true
      this.$nextTick(() => {
        qrcode.toCanvas(this.$refs.MyCanvas, url)
      })
    },
    // 封装获取数据接口
    async  getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageEmployee)
      this.EmployeeList = rows
      this.total = total
      // //console.log(this.EmployeeList)
    },
    // 点击页码
    currentChange(newPage) {
      // 切换页码
      this.pageEmployee.page = newPage
      // 更新页面
      this.getEmployeeList()
    },

    // 处理聘用形式数据
    formatEmployment(row, col, cell) {
      // 使用枚举数据进行处理
      const obj = employeeEnum.hireType.find(item => Number(item.id) === Number(cell))
      return obj ? obj.value : '未知形式'
    },
    // 删除员工
    async delEmployee(id) {
      // 二次确认
      await this.$confirm('确定要删除吗')
      // 发送请求
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployeeList()
    },

    // 导出功能
    async exportExcel() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total
      })
      //  准备表头
      const header = ['手机号', '姓名', '入职日期', '聘用形式', '工号']
      // 数据转换
      const data = rows.map(user => {
        // 假设有一个函数
        // 可以接收用户对象, 根据表头顺序
        // 转成数组返回
        return this.convertUserArr(user)
      })
      // console.log(data)
      // 生成文件
      export_json_to_excel({
        header,
        data
      })
    },

    // 转换数据类型
    convertUserArr(user) {
      const newUser = []
      //  准备表头
      const header = ['手机号', '姓名', '入职日期', '聘用形式', '工号']
      // 表头对应关系
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber'
      }
      // 遍历表头, 按顺序, 从用户对象user 当中取出对应的 value 放入数组中
      header.forEach(key => {
        const enkey = dict[key]
        const val = user[enkey]

        if (enkey === 'timeOfEntry') {
          return newUser.push(formatDate(val))
        } else if (enkey === 'formOfEmployment') {
          const obj = employeeEnum.hireType.find(item => item.id === val)
          newUser.push(obj ? obj.value : '未知形式')
        } else {
          newUser.push(val)
        }
      })
      // 返回数据
      return newUser
    }

  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 120px;
  object-fit: cover;
}
</style>
